<?php
class NewcheckinsController extends AppController {

	var $name = 'Newcheckins';
    var $uses = array('Newcheckin','Fullmax10round',
        'LocationNumcksTb','Friendship','FulltrainTonghopWithoutF',
        'FulltrainsULocationTable','Testing','PreLocation','Influence',
        'MaxBase1','InfluenceDem','MaxMi','FulltrainsULocationSobanTable');
   	var $helpers = array('Html', 'Form',  'Ajax','flashChart');
    
    function pre_db(){
         //khong gioi han thoi gian xu ly
        set_time_limit( 360000000);
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 3600000);
        
        date_default_timezone_set('Asia/Taipei');
        $b=time();
        $this->set(compact('b'));
        
// tim dia diem "hot" voi threshold lay tu nhug thi nghiem truoc
        $this->LocationNumcksTb->recursive=-1;
        $hots=$this->LocationNumcksTb->find('list',array(
                'order'=>array('num_cks'=>'desc'),
                'fields'=>array('location_id','location_id'),
                'conditions'=>array(
                    'num_cks >=? '=>array(85)//,
                    )
          ));
// danh sach cac dia diem de xet        
        $this->LocationNumcksTb->recursive=-1;
        $ls=$this->LocationNumcksTb->find('list',array(
                'order'=>array('num_cks'=>'asc'),
                'fields'=>array('location_id','location_id')
        ));
//xet tung dia diem
        foreach($ls as $l){
            $this->Newcheckin->recursive=-1;
            $users=$this->Newcheckin->find('list',array(
                'conditions'=>array('location_id'=>$l),
                'fields'=>array('user_id','user_id')
            )); 
            $this->Friendship->recursive=-1;
            $fs=$this->Friendship->find('list',array(
                'conditions'=>array('user_id'=>$users),
                'fields'=>array('withuser','withuser')));
             foreach($fs as $f){
                $this->PreLocation->recursive=-1;
                //neu ton tai du lieu luu trong csdl truoc do thi bo qua
                $co=$this->PreLocation->find('first',
                        array('conditions'=>array('location_id'=>$l,'user_id'=>$f)));
                if(empty($co)){
                    $kq=$this->predict($f,$l,$hots);
                    $this->LocationNumcksTb->query("insert into pre_locations(user_id,location_id,yes)
                        values('".$f."','".$l."','".$kq."');
                    ");
                }
             }   
        }
    }
	
    function calculateDistance($lat_a,$lat_b,$long_a,$long_b) {
        if($lat_a==$lat_b&&$long_a==$long_b)
            return 0;
            
        $lat_a = $lat_a * PI()/180;
        $lat_b = $lat_b * PI()/180;
        $long_a = $long_a * PI()/180;
        $long_b = $long_b * PI()/180;
        $distance =
                acos(
                        sin($lat_a ) * sin($lat_b) +
                        cos($lat_a) * cos($lat_b) * cos($long_b - $long_a)
                ) * 6371;
       
        return $distance;
    }
    /** 335,026 rows
    */
    function hot_around10_max(){
        $b=time();
        $this->set(compact('b'));
        $this->FulltrainTonghopWithoutF->recursive=-1;
        $users=$this->FulltrainTonghopWithoutF->find('all');
        
        $this->LocationNumcksTb->recursive=-1;
        $locations=$this->LocationNumcksTb->find('all');
        
        foreach($users as $u){
            $max=0;
            if($u['FulltrainTonghopWithoutF']['max_move']<=10)
                $max=10;
            else 
                $max=$u['FulltrainTonghopWithoutF']['max_move'];
            foreach($locations as $l){
                $distance=abs($this->calculateDistance(
                    $u['FulltrainTonghopWithoutF']['x'],
                    $l['LocationNumcksTb']['x'],
                    $u['FulltrainTonghopWithoutF']['y'],
                    $l['LocationNumcksTb']['y']
                ));
                if($distance<=$max)
                    $this->LocationNumcksTb->query("
                        insert into fullmax10rounds(
                                user_id, location_id,
                                x,y, distance, num_cks)
                            values('".$u['FulltrainTonghopWithoutF']['user_id']."',
                                    '".$l['LocationNumcksTb']['location_id']."',
                                    '".$l['LocationNumcksTb']['x']."',
                                    '".$l['LocationNumcksTb']['x']."',
                                    '".$distance."',
                                    '".$l['LocationNumcksTb']['num_cks']."');
                    ");
                
            }
                
        }
        
    }
    
    /**
     * Ham de tim nut co khac biet lon nhat voi tap hop dang xet
     * @param u1  tap hop dang xet
     * @param infnode cac quan he
     * 
     * @return  gia tri cua nut co khac biet lon nhat
     * */
    function Maxdiff1($u1,$infnodes){
        //set no limitation about time execution
        ini_set('max_execution_time', 0);
        
        $n=count($infnodes);
      
        $indexUser=-1;
        $indexArray=0;
        $dem=0;
        $max=0;
        for($i=0;$i<$n;$i++){
            if($i==0){
             //xet o vong lap dau tien, gan dem=1 va gia tri dau tien la max tam thoi
                if(!in_array($infnodes[0]['Result']['u2'],$u1)){
                    $dem=1;
                    $max=1;
                    $indexUser=$infnodes[0]['Result']['u1'];
                    
                }
            }
            else{
                if($infnodes[$i]['Result']['u1']==$infnodes[$i-1]['Result']['u1']){
                    //truong hop cung user voi du lieu o vong lap truoc
                    if(!in_array($infnodes[$i]['Result']['u2'],$u1)){
                        $dem++;
                        if($dem>$max){
                            $indexUser=$infnodes[$i]['Result']['u1'];
                            $max=$dem;
                            $indexArray=$i;
                        }
                    }
                }else{
                    //neu qua user moi thi khoi tao dem=0;
                    $dem=0;
                    if(!in_array($infnodes[$i]['Result']['u2'],$u1))
                        $dem=1;
                }
            }
            
        }
        return $indexUser;
    }
    /** 
     * 
     * Tim dia diem hot_regions xung quanh max_move cua users
     * 
    **/
    function hot_his_maxdis_fr_avg_devdis_dis_real(){
        $this->Testingfull->recursive=-1;
        ///13422
        $t=$this->Testingfull->find('all',array(
            'fields'=>array('user_id','location_id','yes')
            //,'conditions'=>array('yes'=>0)
            ));
        $n=count($t);
    
       
        for($i=0;$i<$n;$i++){
            $this->Checkinstrain->recursive=-1;
            
            $t_predicted=$this->Checkinstrain->find('list',
                array(
                    'conditions'=>array('user_id'=>$t[$i]['Testingfull']['user_id'])
                    ,'fields'=>array('location_id','location_id')
                    //,                    'order'=>array('c'=>'desc')
                    //,                    'limit'=>2
                    ));
            
            $this->LocationTrain->recursive=-1;
            $hots=$this->LocationTrain->find('list',array(
                'order'=>array('num_checks'=>'desc'),
                'fields'=>array('location_id','location_id'),
                'limit'=>20));
            //$t_predicted=$t_predicted['Newcheckin']['location_id'];;
        
                    if(in_array($t[$i]['Testingfull']['location_id'],$t_predicted))
                    {
                            
                            $this->Testingfull->query("
                                update testingfulls set 
                                    hpm=1
                                    where location_id='".$t[$i]['Testingfull']['location_id']."'
                                        and user_id=".$t[$i]['Testingfull']['user_id']);
                        
                    }else{
                          if(in_array($t[$i]['Testingfull']['location_id'],$hots))
                          {
                            
                            $this->Testingfull->query("
                                update testingfulls set 
                                    hpm=1
                                    where location_id='".$t[$i]['Testingfull']['location_id']."'
                                        and user_id=".$t[$i]['Testingfull']['user_id']);
                          }else
                          {
    
       $this->TrainTonghopWithoutF->recursive=-1;
       //tim dia phuong user hay toi nhat
       $f_dis_user=$this->TrainTonghopWithoutF->find('first',
            array(
                'conditions'=>array(
                    'user_id'=>$t[$i]['Testingfull']['user_id'])));
       
       $this->TrainsULocationTable->recursive=-1;
       $t_2latents=$this->TrainsULocationTable->find('all',
                array(
                    'conditions'=>array('user_id'=>$t[$i]['Testingfull']['user_id'])
           //         ,'fields'=>array('location_id','location_id')
                    ,                    'order'=>array('num_checks'=>'desc')
                    ,                    'limit'=>2
                    ));
      $this->Location->recursive=-1;
      $ls_considered=$this->Location->find('first',array(
            'conditions'=>array('id'=>$t[$i]['Testingfull']['location_id']),
            'fields'=>array('x','y')));
     //  print_r($t_2latents);
   //  array_values  ($t_2latents);   
       $k1=count($t_2latents);
  //    print_r($t_2latents);
       //xac dinh neu tim duoc thi ngat ra khoi vong lap luon
       $ngat=0;
       foreach($t_2latents as $b)
       {
       
            $kc1=abs($this->calculateDistance(
            $b['TrainsULocationTable']['x'],
            $ls_considered['Location']['x'],
            $b['TrainsULocationTable']['y'],
            $ls_considered['Location']['y']
                ));
            //neu khoang cach di chuyen dc so sanh voi 
            //kc-->avg move
            //max_move--> khoang cach di chuyen xa nhat
            //nho hon thi ta bao co the user se den do
            if(
                $f_dis_user['TrainTonghopWithoutF']['kc']
                    >=$kc1)
            {
                 $this->Testingfull->query("
                         update testingfulls set 
                                    hpm=1
                                    where location_id='".$t[$i]['Testingfull']['location_id']."'
                                        and user_id=".$t[$i]['Testingfull']['user_id']);
                 $ngat=1;
                 break;
            }
       }
       
       //neu da tim duoc o tren thi bo qua
  
    if($ngat==0)
    {
       $this->Friendship->recursive=-1;
       $fs=$this->Friendship->find('list',
                 array('fields'=>array('withuser','withuser'),
                       'conditions'=>array('user_id'=>$t[$i]['Testingfull']['user_id'])));
       $this->TrainTonghopWithoutF->recursive=-1;
       $f_dis=$this->TrainTonghopWithoutF->find('all',
                                array('conditions'=>array('user_id'=>$fs)));
       $chay=count($f_dis);
       for($k=0;$k<$chay;$k++)
       {
            $khoang_cach=abs($this->calculateDistance(
                 $f_dis[$k]['TrainTonghopWithoutF']['x'],
                  $ls_considered['Location']['x'],
                 $f_dis[$k]['TrainTonghopWithoutF']['y'],
                 $ls_considered['Location']['y']
             ));
             if(($f_dis_user['TrainTonghopWithoutF']['kc'])>=$khoang_cach)
             {
                   $this->Testingfull->query("
                         update testingfulls set 
                                    hpm=1
                                    where location_id='".$t[$i]['Testingfull']['location_id']."'
                                        and user_id=".$t[$i]['Testingfull']['user_id']);
                    break;
             }
                                    
                                   
        }
    }
                           
                            
                          }
                 
                    }
                   
            
          
        }
        //$this->set(compact('chinhxac'));
    }
/**
 * Ham predict($user_id,$location_id,$hots) du doan user co den dia diem da cho
 * 
 * @param user_id       User se xet
 * @param location_id   Location de du doan
 * @param hots          Vung hot regions danh cho all users
 * 
 * @return  1,0         1: du doan user den, 0: du doan user khong den dia diem da cho
 * 
 * Ham duoc xay dung tren co so model voi xac suat dung 
 * max=91% for 100 rows (96% yes, 86% no), 
 * 88% for testing data set
 * */
    
    function predict($user_id,$location_id,$hots){

    
        $this->Newcheckin->recursive=-1;
        //tim lich su di chuyen cua user    
        $his=$this->Newcheckin->find('list',
                array(
                    'conditions'=>array('user_id'=>$user_id)
                    ,'fields'=>array('location_id','location_id')
                    //,                    'order'=>array('c'=>'desc')
                    //,                    'limit'=>2
                )
        );
/** if so 1, xet lich su di chuyen cua user */        
        if(in_array($location_id,$his))
            return 1;
/** ELSE so 1 */
        else
        {
/** if so 2, xet xem dia phuong dang xet co nam trong hot regions */
            if(in_array($location_id,$hots))
                return 1;
/** else so 2 */
            else          
            {
       
                $this->Friendship->recursive=-1;
                $fs=$this->Friendship->find('list',
                 array('fields'=>array('withuser','withuser'),
                       'conditions'=>array('user_id'=>$user_id)));
       
                $this->Newcheckin->recursive=-1;
                $f_predicted=$this->Newcheckin->find('list',
                        array(
                        'conditions'=>array('user_id'=>$fs)
                    ,                    'fields'=>array('location_id','location_id')
                ));
/** if so 3, xet history cua ban */
                if(in_array($location_id,$f_predicted))
                    return 1;
/** ELSE so 3, bat dau xet den khoang cach "bounded regions" */
                else{
                       
//tim dia phuong user hay toi nhat
                        $this->FulltrainTonghopWithoutF->recursive=-1;
                        $f_dis_user=$this->FulltrainTonghopWithoutF->find('first',
                            array(
                            'conditions'=>array(
                            'user_id'=>$user_id))
                        );

                        $this->FulltrainsULocationTable->recursive=-1;
                        $t_2latents=$this->FulltrainsULocationTable->find('all',
                            array(
                                'conditions'=>array('user_id'=>$user_id)
                        //         ,'fields'=>array('location_id','location_id')
                             ,            'order'=>array('num_checks'=>'desc')
                                ,           'limit'=>1
                        ));
                        $this->LocationNumcksTb->recursive=-1;
                        $ls_considered=$this->LocationNumcksTb->find('first',array(
                            'conditions'=>array(
                                'num_cks >= ? '=>array(5),
                                'location_id'=>$location_id),
                            'fields'=>array('x','y'))
                        );
                        $k1=count($t_2latents);
/** FOR 2, xet nhug dia diem thuong toi cua user va bounded region*/
                        foreach($t_2latents as $b)
                        {
       
                            $kc1=abs($this->calculateDistance(
                                 $b['FulltrainsULocationTable']['x'],
                                $ls_considered['LocationNumcksTb']['x'],
                                $b['FulltrainsULocationTable']['y'],
                                $ls_considered['LocationNumcksTb']['y']
                             ));
                            $max=0;
                            if($f_dis_user['FulltrainTonghopWithoutF']['max_move']<=10)
                                $max=10;
                            else
                                $max=$f_dis_user['FulltrainTonghopWithoutF']['max_move'];
                          
/** IF 4, du doan nam trong bounded region cua user */
                            if($max>=$kc1)
                                return 1;
                        } /** HET FOR 2*/

                        $this->FulltrainTonghopWithoutF->recursive=-1;
                        $f_dis=$this->FulltrainTonghopWithoutF->find('all',
                                array('conditions'=>array('user_id'=>$fs)));
                        $chay=count($f_dis);
/**  FOR 3, chay qua tung BAN **/
                        for($k=0;$k<$chay;$k++)
                        {
                                $khoang_cach=abs($this->calculateDistance(
                                    $f_dis[$k]['FulltrainTonghopWithoutF']['x'],
                                    $ls_considered['LocationNumcksTb']['x'],
                                    $f_dis[$k]['FulltrainTonghopWithoutF']['y'],
                                    $ls_considered['LocationNumcksTb']['y']
                                ));
                                   $max=0;
                  //      if($chan==0){
                                if($f_dis_user['FulltrainTonghopWithoutF']['max_move']<=10)
                                    $max=10;
                                else
                                    $max=$f_dis_user['FulltrainTonghopWithoutF']['max_move'];
                      
/** IF 5, du doan cac hot regions trong bounded region of friends * */
                                if($max>=$khoang_cach)
                                    return 1;                                    
                                   
                        }/** HET FOR 3**/
                }/** HET IF 3**/
                            
                         
                 
            }/** HET ELSE 2**/
                   
            
          
        }/** HET ELSE 1**/
//neu khong nam trong cac vung da cho, nghia la du doan user se khong den
    return 0;
    }/** HET FUNCTION**/
	/** 
	Tao bang influences(location_id, user_id, inf)
	*/
	function influence($location_id){
//tim user da den location
		$this->Newcheckin->recursive=-1;
        $users=$this->Newcheckin->find('list',array(
                'conditions'=>array('location_id'=>$location_id),
                'fields'=>array('user_id','user_id')
        ));
//Xet tung user da den location
		foreach($users as $u){
//tim nhung ban be cua user
			$this->Friendship->recursive=-1;
            $fs=$this->Friendship->find('list',array(
                'conditions'=>array('user_id'=>$u),
                'fields'=>array('withuser','withuser')));
//tim  nhung  ban be du doan se den dia diem
			$this->PreLocation->recursive=-1;
			$influenced_f=$this->PreLocation->find('list',array(
				'conditions'=>array('location_id'=>$location_id,'user_id'=>$fs,'yes'=>1),
				'fields'=>array('user_id','user_id')));
//luu nhung nguoi duoc du doan se den dia diem (nhung nguoi bi anh huong)
			foreach($influenced_f as $inf){
				$this->PreLocation->query("insert into influences(location_id, user_id, inf) 
					values('".$location_id."','".$u."','".$inf."');");
			}
        }
	}
	
    
    /** 
	Tao bang influences(location_id, user_id, inf)
	*/
	function influence_all($location_id,$k){
//tim user da den location
		$this->Newcheckin->recursive=-1;
        $users=$this->Newcheckin->find('list',array(
                'conditions'=>array('location_id'=>$location_id),
                'fields'=>array('user_id','user_id')
        ));
//Xet tung user da den location
		foreach($users as $u){
//tim nhung ban be cua user
			$this->Friendship->recursive=-1;
            $fs=$this->Friendship->find('list',array(
                'conditions'=>array('user_id'=>$u),
                'fields'=>array('withuser','withuser')));
//tim  nhung  ban be du doan se den dia diem
			$this->PreLocation->recursive=-1;
			$influenced_f=$this->PreLocation->find('list',array(
				'conditions'=>array('location_id'=>$location_id,'user_id'=>$fs,'yes'=>1),
				'fields'=>array('user_id','user_id')));
//luu nhung nguoi duoc du doan se den dia diem (nhung nguoi bi anh huong)
			foreach($influenced_f as $inf){
				$this->PreLocation->query("insert into influences(location_id, user_id, inf) 
					values('".$location_id."','".$u."','".$inf."');");
			}
        }
	}
	//tao bang max_base1(location_id, user_id, inf)
	/*
	CREATE TABLE  `max_base1` (
 `location_id` VARCHAR( 30 ) NOT NULL ,
 `user_id` INT( 11 ) NOT NULL ,
 `inf` INT( 11 ) NOT NULL ,
 `id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (  `id` )
) AUTO_INCREMENT =1
	*/
	function maxinf_baseline1($location_id){
		$this->Influence->recursive=-1;
//		$dulieu=$this->PreLocation->find('all',array('conditions'=>array('location_id'=>$location_id)));
		$chudong=$this->Influence->find('list',array(
			'conditions'=>array('location_id'=>$location_id),
			'fields'=>array('user_id','user_id')));
		$bidong=$this->Influence->find('list',array(
			'conditions'=>array('location_id'=>$location_id),
			'fields'=>array('inf','inf')));
	//	$bidong=array_unique($bidong);
		
		foreach($chudong as $c){
			$this->Influence->recursive=-1;
			$inf=$this->Influence->find('list',array(
				'conditions'=>array('location_id'=>$location_id,'user_id'=>$c),
				'fields'=>array('inf','inf')));
            foreach($inf as $f){
                $this->Influence->query("insert into max_base1s(location_id,user_id,inf)
                        values ('".$location_id."','".$c."','".$f."');");
            }
            $this->MaxBase1->recursive=-1;
            $inf_after=$this->MaxBase1->find('list',array(
				'conditions'=>array('location_id'=>$location_id),
				'fields'=>array('inf','inf')));
            if($inf_after==$bidong)
                break;
		}
    }
    
    function maxinf_mi($location_id,$k){

//danh sach nhung nguoi chu dong
		$this->Influence->recursive=-1;
		$chudong=$this->Influence->find('list',array(
			'conditions'=>array('location_id'=>$location_id),
			'fields'=>array('user_id','user_id')));
//danh sach nhung nguoi bi dong
		$bidong=$this->Influence->find('list',array(
			'conditions'=>array('location_id'=>$location_id),
			'fields'=>array('inf','inf')));
	
    
//xet phan tu co anh huong nhat xet truoc
        $this->InfluenceDem->recursive=-1;    
    	$maxu=$this->InfluenceDem->find('first',array(
            'fields'=>array('user_id','user_id'),
            'conditions'=>array('location_id'=>$location_id),
            'order'=>array('num'=>'desc'))
        );
        $id_user_max=$maxu['InfluenceDem']['user_id'];
//tim anh huong cua nguoi cao nhat
        $this->Influence->recursive=-1;
		$inf=$this->Influence->find('list',array(
				'conditions'=>array('location_id'=>$location_id,'user_id'=>$id_user_max),
				'fields'=>array('inf','inf')));
        foreach($inf as $f){
                $this->Influence->query("insert into max_mis(location_id,user_id,inf)
                        values ('".$location_id."',
                            '".$id_user_max."','".$f."');");
        }
        
 //xoa phan tu nay ra
        unset($chudong[$id_user_max]);
        
       $i=0;
        while(1){
            $maxtam_user=$this->Maxdiff($chudong,$location_id);
 //xet tam anh houng cua user co maxdiff
            $inf2=$this->Influence->find('list',array(
				'conditions'=>array(
                    'location_id'=>$location_id,
                    'user_id'=>$maxtam_user),
                'fields'=>array('inf','inf'))
            );
 //ghi vo du lieu
            foreach($inf2 as $f){
                $this->Influence->query("insert into max_mis(location_id,user_id,inf)
                        values ('".$location_id."',
                            '".$maxtam_user."','".$f."');");
            }

//cap nhat lai so user da bi anh huong trong he thong
            $inf_after=$this->MaxMi->find('list',array(
                'conditions'=>array('location_id'=>$location_id),
                'fields'=>array('inf','inf')));
//neu so user bi dong da bang so ban dau duoc yeu cau thi thoat
            if($inf_after==$bidong)
                break;
 //xoa user vua xet
            unset($chudong[$maxtam_user]);
            
            if($i>$k)
                break;
            $i++;
        }
        
        
	
    }
    function Maxdiff($chudong, $location_id){
        $us=-1;
        $diffmax=0;
        $khac=0;
        foreach($chudong as $c){
 //tim anh huong cua c
            $n=$this->Influence->find('list',array(
                'conditions'=>array('location_id'=>$location_id,'user_id'=>$c),
                'fields'=>array('inf','inf')
            ));
 //so sanh sai khac tam anh huong voi cai da co
            $m=$this->MaxMi->find('list',array(
                'conditions'=>array('location_id'=>$location_id),
                'fields'=>array('inf','inf')
            ));
            $khac=count(array_diff($n,$m));
          //  print_r($khac);
            if($diffmax<$khac){
               $diffmax=$khac;
               $us=$c;
            }
        }
        return $us;
    }
    /**
     * toc do chay k=21 khoang 4-5p
    */
    function maxinf_mi_caibien($location_id,$k){


/** xet phan tu co do anh huong cao nhat truoc*/    
//xet phan tu co anh huong nhat xet truoc
        $this->InfluenceDem->recursive=-1;    
    	$maxu=$this->InfluenceDem->find('first',array(
            'fields'=>array('user_id','user_id'),
            'conditions'=>array('location_id'=>$location_id),
            'order'=>array('num'=>'desc'))
        );
        $id_user_max=$maxu['InfluenceDem']['user_id'];
//tim anh huong cua nguoi cao nhat
        $this->Influence->recursive=-1;
		$inf=$this->Influence->find('list',array(
				'conditions'=>array('location_id'=>$location_id,'user_id'=>$id_user_max),
				'fields'=>array('inf','inf')));
        foreach($inf as $f){
                $this->Influence->query("insert into max_mis(location_id,user_id,inf)
                        values ('".$location_id."',
                            '".$id_user_max."','".$f."');");
        }
/** ***********************************************************/
        
       	
        $this->Influence->recursive=-1;
        $inf_full=$this->Influence->find('all',array(
			'conditions'=>array(
                'location_id'=>$location_id,
                'NOT'=>array('user_id'=>$id_user_max)),
			'fields'=>array('user_id','inf'),
            'order'=>array('user_id'=>'asc')));
        
        
       $i=0;
       $khong_xet=array();
       $khong_xet[]=$id_user_max;
       
        while(1){
            $inf_before=$this->MaxMi->find('list',array(
                'conditions'=>array('location_id'=>$location_id),
                'fields'=>array('inf','inf')));
                
            $maxtam_user=$this->MaxDifference($inf_before,$inf_full,'Influence');
            
            if($maxtam_user==-1)
                break;
 
 
 //xet tam anh houng cua user co maxdiff
            $inf2=$this->Influence->find('list',array(
				'conditions'=>array(
                    'location_id'=>$location_id,
                    'user_id'=>$maxtam_user),
                'fields'=>array('inf','inf'))
            );
 //ghi vo du lieu
            foreach($inf2 as $f){
                $this->Influence->query("insert into max_mis(location_id,user_id,inf)
                        values ('".$location_id."',
                            '".$maxtam_user."','".$f."');");
            }

          
            if($i>$k)
                break;
            $i++;
            
            /** cap nhat lai danh sach inf_full gom nhung influential=>influenced chua xet*/
            $khong_xet[]=$maxtam_user;
            $inf_full=$this->Influence->find('all',array(
			     'conditions'=>array(
                    'location_id'=>$location_id,
                    'NOT'=>array('user_id'=>$khong_xet)),
			     'fields'=>array('user_id','inf'),
                 'order'=>array('user_id'=>'asc'))
            );
        }
        
        
	
    }
    /**
     * function MaxDifference($ed_timduoc array,$infnodes,$tenmodel)
     * @param   $ed_timduoc array
     * @param   $infnodes   array 2 chieu: user_id, inf
     * @param   $tenmodel   char    Ten model chua du lieu cua $infnodes
     * 
     * @return  chiso_user_id co do khac biet cao nhat, -1: neu khong tim thay, <>1 neu tim thay
     * */
    function MaxDifference($ed_timduoc,$infnodes,$tenmodel){
        //set no limitation about time execution
        ini_set('max_execution_time', 0);
        
        $n=count($infnodes);
    
        $indexUser=-1;
        $indexArray=0;
        $dem=0;
        $max=0;
        /** chay xet het cac du lieu trong $infnodes,
         * du lieu co dinh dang  $infnodes[$i][$tenmodel]['user_id'], $infnodes[$i][$tenmodel]['inf']
         */
        for($i=0;$i<$n;$i++){
            /** xet o vong lap dau tien, gan dem=1 va gia tri dau tien la max tam thoi */
            if($i==0){
                /** xet phan tu dau tien co khac voi tap da co khong*/            
                if(!in_array($infnodes[0][$tenmodel]['inf'],$ed_timduoc)){
                    /** do khac biet la 1*/
                    $dem=1;
                    //gan tam cho gia tri khac biet lon nhat la 1
                    $max=1;
                    /** cho tam phan tu dau tien la max*/
                    $indexUser=$infnodes[0][$tenmodel]['user_id'];
                    
                }
            }
            /** xet nhung phan tu ke tiep voi i>=1*/
            else{
                /** neu phan tu ke tiep cung duoc user de xet truoc do*/
                if($infnodes[$i][$tenmodel]['user_id']==$infnodes[$i-1][$tenmodel]['user_id']){
                    /** neu du lieu giong nhau thi tang bien dem+1*/
                    if(!in_array($infnodes[$i][$tenmodel]['inf'],$ed_timduoc)){
                        $dem++;
                        /** sau khi cong, so sanh voi gia tri max tam, neu lon hon thi gan max= dem*/
                        if($dem>$max){
                            /** cap nhat lai index nguoi dug co gia tri max, va gia tri max*/
                            $indexUser=$infnodes[$i][$tenmodel]['user_id'];
                            $max=$dem;
                            /** luu lai thoi diem co gia tri max*/
                            $indexArray=$i;
                        }
                    }
                }else{/** neu khong phai user xet truoc do thi qua gia tri moi*/
                    $dem=0;
                    if(!in_array($infnodes[$i][$tenmodel]['inf'],$ed_timduoc)){
                        $dem=1;
                        if($max==0){
                            $max=$dem;
                            $indexUser=$infnodes[$i][$tenmodel]['user_id'];
                            $indexArray=$i;
                        }
                    }
                }
            }
            
        }
        /** chay het vong lap thi co ket qua da xet*/
        return $indexUser;
    
    }
	function max(){
	   $maxtam_user=$this->Maxdiff($chudong,$location_id);
	}
		/*
			$bidong_daco=array_unique(array_merge($array1, $array2));
			if($bidong_daco==$bidong)
				break;
		*/
		
	
    function chay1(){
        set_time_limit( 360000000);
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 3600000);
        
        date_default_timezone_set('Asia/Taipei');
        $b=time();
        $this->set(compact('b'));
      

        //$lo=array('GRID_177_309','GRID_172_295','GRID_415_148','GRID_177_291','GRID_350_161');
        $lo=array('GRID_350_105');
        //print_r($lo);
        $n=count($lo);
        for($i=0;$i<$n;$i++){
            $this->influence($lo[$i]);
        }
    }
    function chay2(){
        set_time_limit( 360000000);
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 3600000);
        
        date_default_timezone_set('Asia/Taipei');
        $b=time();
        $this->set(compact('b'));
        
     //   $lo=array('GRID_177_309');
        //print_r($lo);
        
            $this->maxinf_baseline1('c');
        
    }
	function chay(){
        set_time_limit( 360000000);
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 3600000);
        
        date_default_timezone_set('Asia/Taipei');
        $b=time();
        $this->set(compact('b'));
        
     //   $lo=array('GRID_177_309');
        //print_r($lo);
        
            $this->influence('GRID_177_309');
        
    }
    
    function kusers($location_id,$k){
        $this->MaxMi->recursive=-1;
      
        $us=array();
        $dulieu=$this->MaxMi->find('list',array(
            'conditions'=>array('location_id'=>$location_id),
            'fields'=>array('user_id','user_id')));
        //print_r($dulieu);
        //print_r()
        $i=0;
        //$n=count($dulieu);
        foreach($dulieu as $d){
            $us[]=$d;
            $influenced=$this->MaxMi->find('list',array(
                    'conditions'=>array('location_id'=>$location_id,'user_id'=>$us),
                    'fields'=>array('inf','inf')));
            $this->MaxMi->query("insert into experiments (location_id, user_id, k, num_inf) 
                    values('".$location_id."','".$d."','".$i."',".count($influenced).");");
            if($i>$k)
                break;
            $i++;
        }
        print_r($i.' k='.$k);
     }
    
    function thucnghiem(){
        
        $this->baseline1_all('GRID_177_309',20);
        $this->baseline2_all('GRID_177_309',20);
    //   $this->kusers('GRID_177_309',20);
      //  print_r($c);
    }
    /**
     * ham baseline chon user den thuog xuyen o location
     * ham full chay ngay tu dau khong can lay du lieu co san trong csdl
     * 
     * */
    function baseline1_all($location_id, $k){
        $this->FulltrainsULocationTable->recursive=-1;
        $us= $this->FulltrainsULocationTable->find('list',array(
            'conditions'=>array('location_id'=>$location_id),
            'order'=>array('num_checks'=>'desc'),
            'fields'=>array('user_id','user_id'),
            'limit'=>$k));
        
        $this->LocationNumcksTb->recursive=-1;
        $hots=$this->LocationNumcksTb->find('list',array(
                'order'=>array('num_cks'=>'desc'),
                'fields'=>array('location_id','location_id'),
                'conditions'=>array(
                    'num_cks >=? '=>array(85)//,
                    )
          ));
                    
        $this->Friendship->recursive=-1;
        $fs=$this->Friendship->find('list',array(
            'conditions'=>array('user_id'=>$us),
            'fields'=>array('withuser','withuser')));
            
        
               
        /**
         * du doan duong di cua nhung nguoi ban va luu vao csdl
         * */
        foreach($fs as $f){
            
            //xet trong truong hop chua duoc du doan trong csdl tu truoc
            $this->PreLocation->recursive=-1;
            $xet1=$this->PreLocation->find('first',
                        array('conditions'=>array('location_id'=>$location_id,'user_id'=>$f)));
            if(empty($xet1)){
                $kq=$this->predict($f,$location_id,$hots);
                $this->PreLocation->query("insert into pre_locations(user_id,location_id,yes)
                        values('".$f."','".$location_id."','".$kq."');
                    ");
            }
        }
        /**
         * tao bang luu cac anh huong
         * */
       
        
       // if(empty($xet2)){                
      
        $considered_u=array();
        $i=1;
            foreach($us as $u){
                
                $this->Influence->recursive=-1;
                $xet2=$this->Influence->find('first',
                        array('conditions'=>array('location_id'=>$location_id,'user_id'=>$u)));
                
                /** trong truong hop chua co du lieu tam anh huong cua user_iddang xet thi chay de tim*/        
                if(empty($xet2)) {       
//tim nhung ban be cua user
                    $this->Friendship->recursive=-1;
                    $fs_new=$this->Friendship->find('list',array(
                        'conditions'=>array('user_id'=>$u),
                        'fields'=>array('withuser','withuser')));
//tim  nhung  ban be du doan se den dia diem
                    $this->PreLocation->recursive=-1;
                    $influenced_f=$this->PreLocation->find('list',array(
				        'conditions'=>array('location_id'=>$location_id,'user_id'=>$fs_new,'yes'=>1),
				        'fields'=>array('user_id','user_id')));
//luu nhung nguoi duoc du doan se den dia diem (nhung nguoi bi anh huong)
			         foreach($influenced_f as $inf){
			     
				        $this->PreLocation->query("insert into influences(location_id, user_id, inf) 
					       values('".$location_id."','".$u."','".$inf."');");
			         }
                }
               
                $considered_u[]=$u;
                $tam_anhhuong=$this->Influence->find('list',array(
                    'conditions'=>array('user_id'=>$considered_u,'location_id'=>$location_id),
                    'fields'=>array('inf','inf')));
                $this->PreLocation->query("insert into experimentb1s 
                    (location_id  ,user_id ,k ,num_inf)
                        values('".$location_id."','".$u."','".$i."','".count($tam_anhhuong)."');");
                 $i++;          
                
            }
     //   }
    }


 /**
     * ham baseline chon user co so friends nhieu nhat
     * ham full chay ngay tu dau khong can lay du lieu co san trong csdl
     * 
     * */
    function baseline2_all($location_id, $k){
        $this->FulltrainsULocationSobanTable->recursive=-1;
        $us= $this->FulltrainsULocationSobanTable->find('list',array(
            'conditions'=>array('location_id'=>$location_id),
            'order'=>array('num_fs'=>'desc'),
            'fields'=>array('user_id','user_id'),
            'limit'=>$k));
        
        $this->LocationNumcksTb->recursive=-1;
        $hots=$this->LocationNumcksTb->find('list',array(
                'order'=>array('num_cks'=>'desc'),
                'fields'=>array('location_id','location_id'),
                'conditions'=>array(
                    'num_cks >=? '=>array(85)//,
                    )
          ));
                    
        $this->Friendship->recursive=-1;
        $fs=$this->Friendship->find('list',array(
            'conditions'=>array('user_id'=>$us),
            'fields'=>array('withuser','withuser')));
            
        
               
        /**
         * du doan duong di cua nhung nguoi ban va luu vao csdl
         * */
        foreach($fs as $f){
            
            //xet trong truong hop chua duoc du doan trong csdl tu truoc
            $this->PreLocation->recursive=-1;
            $xet1=$this->PreLocation->find('first',
                        array('conditions'=>array('location_id'=>$location_id,'user_id'=>$f)));
            if(empty($xet1)){
                $kq=$this->predict($f,$location_id,$hots);
                $this->PreLocation->query("insert into pre_locations(user_id,location_id,yes)
                        values('".$f."','".$location_id."','".$kq."');
                    ");
            }
        }
        /**
         * tao bang luu cac anh huong
         * */
       
        
       // if(empty($xet2)){                
      
        $considered_u=array();
        $i=1;
            foreach($us as $u){
                
                $this->Influence->recursive=-1;
                $xet2=$this->Influence->find('first',
                        array('conditions'=>array('location_id'=>$location_id,'user_id'=>$u)));
                
                /** trong truong hop chua co du lieu tam anh huong cua user_iddang xet thi chay de tim*/        
                if(empty($xet2)) {       
//tim nhung ban be cua user
                    $this->Friendship->recursive=-1;
                    $fs_new=$this->Friendship->find('list',array(
                        'conditions'=>array('user_id'=>$u),
                        'fields'=>array('withuser','withuser')));
//tim  nhung  ban be du doan se den dia diem
                    $this->PreLocation->recursive=-1;
                    $influenced_f=$this->PreLocation->find('list',array(
				        'conditions'=>array('location_id'=>$location_id,'user_id'=>$fs_new,'yes'=>1),
				        'fields'=>array('user_id','user_id')));
//luu nhung nguoi duoc du doan se den dia diem (nhung nguoi bi anh huong)
			         foreach($influenced_f as $inf){
			     
				        $this->PreLocation->query("insert into influences(location_id, user_id, inf) 
					       values('".$location_id."','".$u."','".$inf."');");
			         }
                }
               
                $considered_u[]=$u;
                $tam_anhhuong=$this->Influence->find('list',array(
                    'conditions'=>array('user_id'=>$considered_u,'location_id'=>$location_id),
                    'fields'=>array('inf','inf')));
                $this->PreLocation->query("insert into experimentb2s 
                    (location_id  ,user_id ,k ,num_inf)
                        values('".$location_id."','".$u."','".$i."','".count($tam_anhhuong)."');");
                 $i++;          
                
            }
     //   }
    }
    
    
    /**
     * chay voi du lieu influence da co san*
    */
    function baseline1($location_id, $k){
        $this->FulltrainsULocationTable->recursive=-1;
        $us= $this->FulltrainsULocationTable->find('list',array(
            'conditions'=>array('location_id'=>$location_id),
            'order'=>array('num_checks'=>'desc'),
            'fields'=>array('user_id','user_id'),
            'limit'=>$k));
        
      $i=0;
        $considered_u=array();
            foreach($us as $u){
                
               
                $considered_u[]=$u;
                 $this->Influence->recursive=-1;
                $tam_anhhuong=$this->Influence->find('list',array(
                    'conditions'=>array('user_id'=>$considered_u,'location_id'=>$location_id),
                    'fields'=>array('inf','inf')));
                $this->PreLocation->query("insert into experimentb1s 
                    (location_id  ,user_id ,k ,num_inf)
                        values('".$location_id."','".$u."','".$i."','".count($tam_anhhuong)."');");
                 $i++;          
                
            }
     //   }
    }
/**
     * chay voi du lieu influence da co san*
    */
    function baseline2($location_id, $k){
        $this->FulltrainsULocationSobanTable->recursive=-1;
        $us= $this->FulltrainsULocationSobanTable->find('list',array(
            'conditions'=>array('location_id'=>$location_id),
            'order'=>array('num_fs'=>'desc'),
            'fields'=>array('user_id','user_id'),
            'limit'=>$k));
        
        
      $i=0;
        $considered_u=array();
            foreach($us as $u){
                
               
                $considered_u[]=$u;
                 $this->Influence->recursive=-1;
                $tam_anhhuong=$this->Influence->find('list',array(
                    'conditions'=>array('user_id'=>$considered_u,'location_id'=>$location_id),
                    'fields'=>array('inf','inf')));
                $this->PreLocation->query("insert into experimentb2s 
                    (location_id  ,user_id ,k ,num_inf)
                        values('".$location_id."','".$u."','".$i."','".count($tam_anhhuong)."');");
                 $i++;          
                
            }
     //   }
    }
    /**
     * giai thuat tinh tam anh huonng cua k user de dung giai thuat de optimize
    */
    function im_all($location_id, $k){
        //$this->maxinf_mi($location_id,$k);
        $us=$this->MaxMi->find('list',array(
            'conditions'=>array('location_id'=>$location_id),
            'fields'=>array('user_id','user_id'),'order'=>array('id'=>'asc')));
        $considered_u=array();
        $i=0;
        foreach($us as $u){
            $considered_u[]=$u;
            $this->Influence->recursive=-1;
            $tam_anhhuong=$this->Influence->find('list',array(
                    'conditions'=>array('user_id'=>$considered_u,'location_id'=>$location_id),
                    'fields'=>array('inf','inf')));
            $this->PreLocation->query("insert into experiments 
                    (location_id  ,user_id ,k ,num_inf)
                        values('".$location_id."','".$u."','".$i."','".count($tam_anhhuong)."');");
            if($i>$k)
                break;
            $i++;  
        }

        
    }
    function chaychinhthuc(){
         //$lo=array(,'GRID_172_295','GRID_415_148','GRID_177_291','GRID_350_161');
       
      //  $this->influence('GRID_172_295');
        //da thu nghiem xong GRID_177_309,GRID_172_295
        //$this->maxinf_mi_caibien('GRID_177_309',22);
  //      $this->baseline2('GRID_177_309',22);
        
       $this->im_all('GRID_177_309',20);
        // $this->baseline2('GRID_177_309',20);
    }
}
?>